from celery import shared_task
from celery.schedules import crontab
from django.utils import timezone
from django.conf import settings
import random
import string
from .models import HostCredential, Host, City, DataCenter, HostStatistic
import logging

logger = logging.getLogger(__name__)


@shared_task
def update_host_passwords():
    """Task to update all host passwords every 8 hours"""
    hosts = Host.objects.filter(status='active')

    for host in hosts:
        try:
            new_password = ''.join(
                random.choices(
                    string.ascii_letters + string.digits + '!@#$%^&*',
                    k=16
                )
            )

            credential, created = HostCredential.objects.get_or_create(
                host=host,
                defaults={'root_password': new_password}
            )

            if not created:
                credential.root_password = new_password
                credential.save()

            logger.info(f"Updated password for host {host.hostname}")
        except Exception as e:
            logger.error(f"Failed to update password for host {host.hostname}: {str(e)}")


@shared_task
def generate_daily_statistics():
    """Task to generate daily host statistics by city and data center"""
    today = timezone.now().date()

    if HostStatistic.objects.filter(date=today).exists():
        logger.info("Statistics already generated for today")
        return

    cities = City.objects.all()

    for city in cities:
        data_centers = city.data_centers.all()

        for dc in data_centers:
            host_count = dc.hosts.filter(status='active').count()

            HostStatistic.objects.create(
                city=city,
                data_center=dc,
                host_count=host_count,
                date=today
            )

            logger.info(f"Created stats for {dc.name}: {host_count} hosts")


CELERY_BEAT_SCHEDULE = {
    'update-host-passwords-every-8-hours': {
        'task': 'hostmanager.tasks.update_host_passwords',
        'schedule': crontab(minute=0, hour='*/8'),
    },
    'generate-daily-statistics': {
        'task': 'hostmanager.tasks.generate_daily_statistics',
        'schedule': crontab(minute=0, hour=0),
    },
}